<template>
  <el-dialog
    v-model="props.dialogVisible"
    :title="props.title"
    width="600px"
    top="3vh"
    :before-close="() => emit('close')"
  >
    <el-form
      ref="deptEl"
      :model="state.formData"
      label-width="80px"
      :rules="formRules"
    >
      <el-form-item label="上级部门" prop="parentId">
        <el-tree-select
          v-model="state.formData.parentId"
          :data="state.treeData"
          check-strictly
          :props="treeProps"
          :render-after-expand="false"
          style="width: 100%"
        />
      </el-form-item>

      <el-row>
        <el-col :span="12">
          <el-form-item label="部门名称" prop="deptName">
            <el-input
              v-model="state.formData.deptName"
              placeholder="请输入部门名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示排序" prop="orderNum">
            <el-input
              type="number"
              v-model="state.formData.orderNum"
              placeholder="请输入显示排序"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="负责人" prop="leader">
            <el-input
              v-model="state.formData.leader"
              placeholder="请输入负责人"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input
              type="number"
              v-model="state.formData.phone"
              placeholder="请输入联系电话"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="state.formData.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门状态" prop="status">
            <el-radio-group v-model="state.formData.status">
              <el-radio label="0">正常</el-radio>
              <el-radio label="1">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="() => emit('close')">取消</el-button>
        <el-button type="primary" @click="onConfirm"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  defineExpose,
  defineProps,
  defineEmits,
  reactive,
  onMounted,
  ref,
} from 'vue'
import { ElMessage } from 'element-plus'
import { addDept, listDept, updateDept } from '@/api/dept/index'

const deptEl = ref()
const emit = defineEmits(['close'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '',
  },
  isAdd: {
    type: Boolean,
    default: false,
  },
})
const treeProps = {
  value: 'deptId',
  label: 'deptName',
  children: 'children',
}

// 校验数据
const formRules = reactive({
  parentId: [{ required: true, message: '上级部门不能为空', trigger: 'blur' }],
  deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, message: '显示排序不能为空', trigger: 'blur' }],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change'],
    },
  ],
  phone: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur',
    },
  ],
})

// 页面数据
const state = reactive({
  treeData: [],
  formData: {
    parentId: 100,
    deptName: '',
    orderNum: '',
    leader: '',
    phone: '',
    email: '',
    status: '0',
    deptId: '',
  },
})

onMounted(() => {
  getDeptTreeData()
})

// 查询下拉菜单数据
const getDeptTreeData = () => {
  listDept().then((res) => {
    state.treeData = handTree(res.data)
  })
}

// 构造树形结构
const handTree = (list) => {
  return list.reduce((prev, curr, i, arr) => {
    curr.children = arr.filter((item) => item.parentId === curr.deptId)
    if (curr.parentId === 0) {
      prev.push(curr)
    }
    return prev
  }, [])
}

// 确定按钮
const onConfirm = () => {
  console.log(state.formData)
  deptEl.value.validate((valid, fields) => {
    if (valid) {
      if (state.formData.deptId) {
        updateDept(state.formData).then((res) => {
          ElMessage.success('修改成功')
          emit('close', true)
        })
      } else {
        addDept(state.formData).then((res) => {
          ElMessage.success('新增成功')
          emit('close', true)
        })
      }
    }
  })
}

// 回填数据
const setFormData = (form) => {
  state.formData = {
    parentId: 100,
    deptName: '',
    orderNum: '',
    leader: '',
    phone: '',
    email: '',
    status: '0',
    deptId: '',
  }
  if (typeof form === 'object' && form !== null) {
    state.formData = form
  } else if (typeof form === 'number') {
    state.formData.parentId = form
  }
}

defineExpose({
  setFormData,
})
</script>

<style scoped lang="scss">
.tree-border {
  padding: 10px;
  width: 100%;
  border: 1px solid var(--el-color-primary);
  border-radius: 5px;
  min-height: 200px;
  max-height: 400px;
  overflow: auto;
}
</style>
